<template>
  <div class="index ">
    <Card_1 v-if="card_type == 1" :card_msg="card_msg" :isPrev="true"></Card_1>
    <div class="pb15 bgfff" v-else >
      <Card_2 v-if="card_type == 2"
              :card_msg="card_msg"
              @uploadpic="uploadpic"
              :isPrev="true"
      >
      </Card_2>
      <Card_3 v-if="card_type == 3"
              :isPrev="true"
              :card_msg="card_msg">
      </Card_3>
      <Card_4 v-if="card_type == 4" :card_msg="card_msg"></Card_4>
    </div>

    <GetPhoneNumber @next="toCardCase">
      <div class="pt15 card-case">
        <div class="disflex h30 bra_left_15 bg_line_blue cfff fs12 pl15 pr10 lh30 align-cen">
          <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/cardlist.png" alt="" class="w24 h24">
          <span class="pl7">名片夹</span>
        </div>
      </div>
    </GetPhoneNumber>


    <FormId>
      <div class="disflex pl15 pr15 fs18 lh44 textc jsbet bgfff user-btn-group">
        <button class='share_card w165 bradius5 cblue bblue bgfff' open-type="share" hover-class="other-button-hover" style="margin: 0">
          分享名片
        </button>
        <div v-if="type == 0" class="bgblue bradius5 cfff w165 edit-btn" @click="updateMyCard" style="margin: 0">
          编辑名片
        </div>
        <div v-else-if="type != 0 && hasCard" class="bgblue bradius5 cfff w165" @click="SaveToCustomer" style="margin: 0">
          存为客户
        </div>
        <div v-else class="bgblue bradius5 cfff w165" @click="createCard" style="margin: 0">
          创建名片
        </div>
      </div>
    </FormId>


    <view>
      <div class="card_menu fs12 ca8 bgfff borderbox pl10 pr10">
        <div class="clearfix pt15 pb15 disflex operation-box">
          <div class="shadow_gray textc bradius5 pt15 pl15 pr15 h65 mr10 business_card" @click="createCode">
            <p class="pb3">名片码</p>
            <div class="w20">
              <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/ercode.png" alt=" "
                   class="w20 h20">
            </div>
          </div>
          <scroll-view scroll-x scroll-with-animation>
            <div class="disflex scroll-list">
              <div class="shadow_gray textc pt15 pl15 pr15 h65 mr10"
                v-if="type == 0"
                @click="toShowBill">
                <p class="pb7">
                  名片海报
                </p>
                <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/crm/wx_timeline.png" alt=" "
                     class="w20 h20" />
              </div>
              <div class="shadow_gray textc bradius5 pt15 pl15 pr15 h65 mr10" @click="addToAddressBook">
                <p class="pb7">
                  同步到
                </p>
                <p>通讯录</p>
              </div>
              <div class="shadow_gray textc bradius5 pt15 pl15 pr15 h65 mr10" @click="makePhone">
                <p class="disflex align-cen">
                  <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/tel.png" alt=""
                       class="w16 h16">
                  <span class="pl9">拨打电话</span>
                </p>
                <p class="c78 fbold pt7">{{card_msg.tel || '未添加'}}</p>
              </div>
              <div class="shadow_gray textc bradius5 pt15 pl15 pr15 h65 mr10" @click="addWx">
                <p class="disflex align-cen">
                  <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/msg.png" alt=""
                       class="w16 h16">
                  <span class="pl9">添加微信</span>
                </p>
                <p class="c78 fbold pt7">{{card_msg.wx || '未添加'}}</p>
              </div>
              <div class="shadow_gray textc bradius5 pt15 pl15 pr15 h65 mr10">
                <p class="disflex align-cen">
                  <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/product-index/20190425164542.png" alt=""
                       class="w16 h16">
                  <span class="pl9">公司地址</span>
                </p>
                <p class="c78 fbold pt7">{{card_msg.address || '未添加'}}</p>
              </div>
            </div>
          </scroll-view>
        </div>
        <div class="more-info">
          <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/product-index/20190514143457.png" alt="" class="left-img">
        </div>
      </div>

    </view>

    <div class="seen_peo disflex pl15 pr26 fs10 pb15 ca8 jsbet bgfff">
      <div>
        <div class="disflex">
          <img v-for="(v,k) in card_msg.browsePhoto" :key="k" :src="v" alt=""
               mode="aspectFill"
               class="w20 h20 bradius3 mr3">
        </div>
        <p class="lh20">
          已有{{card_msg.browseNum}}人浏览
        </p>
      </div>
      <div class="textc" @click="doThumbs">
        <img :src="isThumbs ? 'http://one-stand.oss-cn-shanghai.aliyuncs.com/product-index/20190418161136.png' : 'https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/like.png' "
             alt="" class="w20 h20 trans2"
        >
        <p>靠谱 <span class="cpurple">{{card_msg.thumbsNum}}</span></p>
      </div>
    </div>
    <!--introduce begin-->
    <div class="bgf5f6 c38 fs16 pl15 pr15">
      <p class="lh44 fs16 fbold">个人简介</p>
      <div class="shadow_gray pl15 pr15 bgfff bradius5">
        <div class="pt15 disflex pb20">
          <img :src="card_msg.picchecked" mode="aspectFill" alt="" class="w40 h40 bradius5 mr15">
          <div class="disinblock">

            <div class='output-audio'>
              <!-- 默认状态 -->
              <div class='audio' v-if="audioArr.bl==false" @click='audioPlay' :data-id="audioArr.id"
                   :data-bl="audioArr.bl">
                <img class='ico'
                     src='https://xcx.quan5fen.com/Public/xcx-hitui/image/imgs-jyh/yuyin-ico.png'/>
              </div>

              <!-- 当前正在播放状态 -->
              <div class='audio' v-if="audioArr.bl==true" @click='audioStop' :data-id="audioArr.id"
                   :data-bl="audioArr.bl">
                <img class='ico'
                     src='https://xcx.quan5fen.com/Public/xcx-hitui/image/imgs-jyh/yuyin-gif.gif'/>
              </div>

            </div>
          </div>


          <span class="fs12 ca8 disflex column-reverse">{{audioArr.time || 0}}"</span>
        </div>
        <div class="fs14 self_introduce lh22"
             :style="{height:seemore?introHeight : '' }"
             v-if="introduce"
        >
          <div class="introduce pb20">
            {{introduce}}
          </div>
        </div>
        <div class="more fs12 ca8 lh40 textc" @click="seemore = !seemore" v-if="moreshow">了解更多</div>
      </div>

    </div>
    <!--introduce end-->
    <!--pic begin-->
    <div class="bgf5f6 c38 fs16" v-if="self_photos.length">
      <p class="lh44 fs16 pl15 fbold">我的照片</p>
      <!-- 没有照片直接不显示此模块，此处不要 -->
      <!-- <div class="textc shadow_gray pl15 pr15 bgfff bradius5" style="height: 104px" v-if="self_photos.length == 0">
        暂无图片
      </div> -->
      <div>
        <img :lazy-load="true"
             :src="v"
             alt=""
             v-for="(v,k) in self_photos"
             :key="k"
             mode="widthFix"
             class="w100p h375"
             @click="previewImage(v)">
      </div>

    </div>
    <!--pic end-->
    <!--bottom-->
    <div class="textc lh42 fs12 ca8 bgf5f6">- 到底了，看看其他的吧 -</div>

    <!--右边悬浮框-->
    <div class="index_float_right trans2 overhidden" >
      <RightFloat></RightFloat>
    </div>

    <div v-if="isShowCourse">
      <addWxCourse :isShow="isShowCourse"
                   @close="isShowCourse=false"
      />
    </div>

    <!--初次登录-->
    <div v-if="!islogin">
      <Login @GetUserInfo="GetUserInfo"></Login>
    </div>
  </div>
</template>

<script>
  let myaudio = wx.createInnerAudioContext();
  myaudio.obeyMuteSwitch = false;

  import RightFloat from '@/components/rightFloat' //
  import GetPhoneNumber from '@/components/getPhoneNumber' //
  import AddWxCourse from '@/components/addWxCourse'
  import Card_1 from '@/components/card_1' //
  import Card_2 from '@/components/card_2' //
  import Card_3 from '@/components/card_3' //
  import Card_4 from '@/components/card_4' //
  import Login from '@/components/login' //
  import FormId from '@/components/formId'

  import { mapActions, mapGetters } from 'vuex';
  import WXAJAX from '../../utils/request'
  import util from '../../utils/index'

  export default {
    data() {
      return {
        islogin: true,
        introduce: '',//介绍
        seemore: false,
        introHeight: '',

        //音频列表
        audioArr: {
          id: '0',
          src: '',
          time: '',
          bl: false,
          startTime: 0,
        },
        card_type: 1,//名片样式
        type: 0,//0我的名片，1别人名片
        card_msg: {     //名片信息
          username: '',
          post: '',
          tel: '',
          company_logo: '',
          picchecked: '',
          company: ''

        },
        wxCode: '',
        loginMsg: {
          rawData: '',
          signature: '',
          encryptedData: '',
          iv: '',
        },
        COMPANYID: 0,
        CARDID: 0,
        moreShow: false,
        self_photos: [],
        isThumbs: 0,//是否点赞
        right_float_show: false,//右边悬浮框
        goType:0,// 0小程序进入，1分享进入
        hasCard: false, //  是否有名片
        isShowCourse: false,
      }
    },

    components: {RightFloat, Card_1, Card_2, Card_3, Card_4, Login, FormId, GetPhoneNumber, AddWxCourse},

    mounted() {
      //获取名片的公司
    },
    onShareAppMessage(e) {
      return {
        title: `您好，我是${this.currentCompany.companyName}的${this.currentCompany.position || ''}${this.currentCompany.name}，敬请惠存!`,
        path: '/pages/index/main?cardId=' + this.CARDID + '&companyId=' + this.COMPANYID + '&goType=1',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        },
        fail(e) {
          console.log('失败分享名片--- ', e);
        }
      }
    },
    onShow() {
      //获取名片的公司
      let lastCardId = this.CARDID;
      let query = this.$root.$mp.query;
      if (query.cardId) {//从分享的名片页面进入
        this.CARDID = query.cardId;
        this.COMPANYID = query.companyId;
        this.goType = query.goType;
        wx.setStorageSync('COMPANYID', query.companyId);
        wx.setStorageSync('CARDID', query.cardId);
        this.$root.$mp.query = [];
      } else {
        this.COMPANYID = wx.getStorageSync('COMPANYID') || 0;
        this.CARDID = wx.getStorageSync('CARDID') || 0;
      }

      this.hasCard = wx.getStorageSync('hasCard');

      if (lastCardId !== this.CARDID || !this.card_msg.cardId) {
        this.inits();
      }
    },
    onHide() {
      myaudio.stop();
    },
    async onPullDownRefresh() {
      // to doing..
      // 停止下拉刷新
      wx.showNavigationBarLoading();
      this.inits(1);
      wx.stopPullDownRefresh();
      setTimeout(function () {
        wx.hideNavigationBarLoading();
      }, 300)
    },
    onPageScroll() {
      this.right_float_show = false;
    },
    computed:{
      ...mapGetters(['currentCompany']),
    },
    methods: {
      ...mapActions(['setCurrentCompany']),
      toShowBill(){
        console.log(this.CARDID)
        wx.navigateTo({
          url: '/pages/showBill/main?cardId=' + this.CARDID
        })
      },
      inits(refresh) {//获取数据
        wx.showLoading();
        WXAJAX.POST({
          cardId: this.CARDID || 1,
          refresh: refresh || '',
        }, '', '/businessCard/cardDetails').then((data, code) => {
          wx.hideLoading();
          if (data) {
            if (data.soundRecording) {
              this.audioArr = {
                bl: false,
                time: data.soundTime || 0,
                id: 1,
                src: data.soundRecording
              };
            } else {
              this.audioArr = {
                bl: false,
                time: 0,
                id: 1,
                src: ''
              };
            }
            this.card_msg = {
              cardId: data.cardId,
              companyId: data.companyId,
              picchecked: data.logo || '',
              username: data.name || '',
              tel: data.phone || '',
              wx: data.personalWx || '',
              company_wx: data.companyWx || '',
              email: data.email || '',
              post: data.position || '',
              company: data.companyName,
              company_logo: data.companyLogo,
              browseNum: data.browseNum,
              thumbsNum: data.thumbsNum,
              address: data.address,
              browsePhoto: data.browsePhoto ? data.browsePhoto.split(',') : [],
            };
            this.introduce = data.briefIntroduction || '';
            this.self_photos = data.photo ? data.photo.split(',') : [];
            this.card_type = data.style + 1;
            this.type = data.cardType;
            this.isThumbs = data.isThumbs;
            wx.setStorageSync('CARDTEL', data.phone);

            this.setCurrentCompany(data);

            this.$nextTick(() => {
              this.getIntroHeight();
            })
          } else if(code != 209) {
            this.card_msg = {};
            wx.showToast({
              title: '获取名片信息失败，请重试！',
              duration: 2000,
              icon: 'none'
            });
          }
        }).catch((err) => {
          this.card_msg = {};
          console.log(err);
          wx.hideLoading();
        });
      },
      toCardCase(){//名片夹
        wx.redirectTo({url:'../cardCase/main'})
      },
      getIntroHeight() {
        let v = this;
        wx.createSelectorQuery().select('.introduce').boundingClientRect(function (rect) {
          if(!rect) return;

          if (rect.height < 107) {
            v.moreShow = false;
          } else {
            v.moreShow = true;
          }
          v.introHeight = rect.height + 'px';
        }).exec()
      },
      //音频播放
      audioPlay(e) {
        var that = this,
          id = e.currentTarget.dataset.id,
          key = e.currentTarget.dataset.key,
          audioArr = that.audioArr,
          vidSrc = audioArr.src;

        if (!vidSrc) {
          return;
        }

        myaudio.src = vidSrc;
        myaudio.autoplay = true;
        myaudio.startTime = 0;

        //切换显示状态
        that.$set(that.audioArr, 'bl', true);
        // audioArr.bl = true;

        //开始监听
        myaudio.onPlay(() => {
          that.audioArr = audioArr;
        });

        //结束监听
        myaudio.onEnded(() => {
          audioArr.bl = false;
          myaudio.stop();
          myaudio.destroy();
          myaudio = wx.createInnerAudioContext();
          myaudio.obeyMuteSwitch = false;
          that.$set(that.audioArr, 'bl', false);
        })

      },
      // 音频停止
      audioStop(e) {
        var that = this,
          key = e.currentTarget.dataset.key,
          audioArr = that.audioArr;
        //切换显示状态
        audioArr.bl = false;

        myaudio.stop();
        myaudio.destroy();
        myaudio = wx.createInnerAudioContext();
        myaudio.obeyMuteSwitch = false;
      },
      createCode(){
        WXAJAX.POST({
          cardId: this.CARDID,
        }, '', '/businessCard/getWxTwoCode').then((data) => {
          wx.navigateTo({url: '/pages/cardCode/main?code='+data})
        }).catch((err) => {
          wx.hideLoading();
        });
      },
      page_turn(url) {//名片夹
        if (url == 'cardCode') {
          wx.setStorageSync({
            wxCodeMsg: {
              name: this.card_msg.name,
              logo: this.card_msg.logo,
              company_logo: this.card_msg.company_logo,
              post: this.card_msg.post,
            }
          })
          wx.navigateTo({url: '../' + url + '/main?companyId=' + this.COMPANYID + '&cardId=' + this.CARDID});
        } else {
          wx.navigateTo({url: '../' + url + '/main'});
        }
        // wx.redirectTo({url:'../'+url+'/main'})
      },
      uploadpic(type) {//card2 选择公司图片

      },
      createCard(){
        util.toMiniProgram('/pages/editCard/main?goType=1&type=add');
      },
      SaveToCustomer() {//存为客户

        if(wx.getStorageSync('token')){
          util.toMiniProgram(`/pages/clientAdd/main?type=userAdd&goType=1&cardId=${this.currentCompany.cardId || ''}&userId=${this.currentCompany.userId || ''}`);
        }else{
          //没有登录，完善信息
          wx.showToast({
            title: '请先完善您的名片信息！',
            icon: 'none',
            duration: 1000
          });
        }
        /*setTimeout(function () {
          wx.navigateTo({url: '../editCard/main'});
        }, 1000);*/

      },
      updateMyCard() {
        wx.navigateTo({url: '../editCard/main?type=edit'})
      },
      addToAddressBook() {//添加到通讯录
        wx.addPhoneContact({
          firstName: this.card_msg.username,
          mobilePhoneNumber: this.card_msg.tel,
          organization: this.card_msg.company,
          success: function (res) {
            console.log('success', res);
          },
          fail: function (err) {
            console.log(err)
          }
        })
      },
      makePhone() {//拨打电话
        this.addCallsPhoneRecord(this.card_msg.cardId); // 好像没用，是underfind
        util.MakePhone(this.card_msg.tel || '');
      },
      addWx() {//添加微信
        let v = this;
        if (v.card_msg.wx) {
          wx.setClipboardData({
            data: v.card_msg.wx,
            success: function (res) {
              wx.getClipboardData({
                success: function (res) {
                  v.isShowCourse =  true;
                  wx.showToast({
                    title: '复制成功'
                  })
                }
              })
            }
          })
        } else {
          wx.showToast({
            title: '还没有添加微信呢！',
            duration: 2000,
            icon: 'none'
          });
        }
      },
      getLoginStatus() {
        let v = this;
        wx.login({
          success: (data) => {
            if (data.code) {
              //保存code
              v.wxCode = data.code;
              v.login();
            } else {
              wx.showToast({
                title: '获取登录状态失败！',
                duration: 2000,
                icon: 'none'
              });
              console.log('获取用户登录状态失败！' + data.errMsg)
            }
          }

        });
      },
      GetUserInfo(msg) {//获取用户信息
        this.islogin = true;
        this.loginMsg = {
          rawData: msg.rawData,
          signature: msg.signature,
          encryptedData: msg.encryptedData,
          iv: msg.iv,
        };
        console.log('用户信息', msg);
        this.getLoginStatus();
        // this.login(msg) ;
      },
      login(msg) {
        WXAJAX.POST({
          code: this.wxCode,
          rawData: this.loginMsg.rawData,
          signature: this.loginMsg.signature,
          encrypteData: this.loginMsg.encryptedData,
          iv: this.loginMsg.iv
        }, '', '/home/wxLogin').then((data) => {
          if (data.token) {
            wx.setStorageSync('token', data.token);
          }
          wx.setStorageSync('loginMsg', this.loginMsg)
        }).catch((err) => {

        });
      },
      previewImage(src) {//点击图片放大
        var v = this;
        wx.previewImage({
          current: src,
          urls: v.self_photos
          // urls必须是数组 不然会报错
        })
      },
      doThumbs() {//点赞
        wx.showLoading();
        WXAJAX.POST({
          cardId: this.CARDID,

        }, '', '/businessCard/doThumbs').then((data) => {

          wx.hideLoading();
          if (this.isThumbs) {
            this.$set(this.card_msg, 'thumbsNum', --this.card_msg.thumbsNum);
          } else {
            this.$set(this.card_msg, 'thumbsNum', ++this.card_msg.thumbsNum);
          }
          this.isThumbs = !this.isThumbs;
        }).catch((err) => {
          wx.hideLoading();
        });
      }
    },
    created() {
      wx.setNavigationBarTitle({
        title: "名片"
      });
      // this.init();
    }
  }
</script>
<style>
  .more-info{
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    height: 20px;
    width: 15px;
    background: white;
    box-shadow:0px 0px 10px 0px rgba(56,56,56,0.1);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .more-info .left-img{
    width: 5px;
    height: 10px;
  }
  .operation-box{
    margin-left: 65px;
    margin-right: 10px;
  }
  .business_card{
    position: absolute;
    box-sizing: border-box;
    left: 0;
    border-radius: 0 50% 50% 0;
    display: flex;
    align-items: center;
    padding-top: 0;
    width: 66px;
  }
  .business_card p{
    writing-mode:tb-rl;
  }
  .index{
    position: relative;
  }
  .user-btn-group > *{
    margin: 0;
  }

  .card_menu{
    position: relative;
  }
  .scroll-list{
    padding: 0 20px 0 10px;
  }
  .scroll-list > div {
    white-space:nowrap;
    box-sizing: border-box;
  }

  .self_introduce {
    min-height: 107px;
    transition: .1s;
    overflow: hidden;
  }

  .self_introduce.higher {
    height: auto;
  }

  .output-audio {
    width: 167px;
    height: 40px;
    position: relative;
    margin-right: 11px;
  }

  .audio::before {
    content: '';
    display: block;
    width: 10px;
    height: 10px;
    background: #F5F5F6;
    position: absolute;
    border: 0.5px solid #E8E8E8;
    border-radius: 4px;
    transform: rotate(45deg);
    border-right-width: 0;
    border-top-width: 0;
    top: 0px;
    bottom: 0;
    left: -6px;
    margin: auto;
  }

  .output-audio .audio {
    padding: 12px 0 12px 17px;
    background: #F5F5F6;
    border: 0.5px solid #E8E8E8;
    position: relative;
    height: 15px;
    border-radius: 5px;
  }

  .output-audio .audio .ico {
    width: 12px;
    height: 17px;
    float: left;
  }

  scroll-view {
    background: #fff;
  }

  .edit-btn{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .card-case{
    position: fixed;
    right: 0;
    top: 20px;
    z-index: 999;
  }
  /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
  ::-webkit-scrollbar
  {
    width: 0px;
    height: 0px;
    background-color: transparent;
  }
  /*定义滚动条轨道 内阴影+圆角*/
  ::-webkit-scrollbar-track
  {
    -webkit-box-shadow: inset 0 0 10px transparent;
    border-radius: 10px;
    background-color: transparent;
  }
  /*定义滑块 内阴影+圆角*/
  ::-webkit-scrollbar-thumb
  {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 10px transparent;
    background-color: transparent;
  }

</style>
